//  Copyright © 2014 Allen County Public Library.

//        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.

package us.in.lib.acpl.Mobile_ACPL;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import us.in.lib.acpl.Mobile_ACPL.models.OverdriveCheckoutsResponse.OverdriveCheckout;
import us.in.lib.acpl.Mobile_ACPL.models.OverdriveMetadata;
import us.in.lib.acpl.Mobile_ACPL.parents.BaseActivity;
import us.in.lib.acpl.Mobile_ACPL.rest.OverdriveClient;

@EActivity(R.layout.overdrive_detail)
public class OverdriveDetailActivity extends BaseActivity{
	
	@RestService
	OverdriveClient client;
	
	@ViewById
	TextView title;
	
	@ViewById
	TextView author;
	
	@ViewById
	TextView expires;
	
	@ViewById
	ImageView coverImage;
	
	@ViewById
	ProgressBar coverBar;
	
	@ViewById
	TextView readButton;
	
	@ViewById
	TextView returnButton;
	
	@ViewById
	ProgressBar readBar;
	
	OverdriveMetadata metadata;
	OverdriveCheckout checkout;
	
	String returnURL;
	String readTemplate;
	String coverURL;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
	}
	
	@AfterViews
	public void afterViews(){
		this.getActionBar().setTitle("   Overdrive");

		
		SharedPreferences prefs = this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
		String overdriveToken = prefs.getString("overdriveToken", null);
		client.setHeader("Authorization",  "Bearer "+overdriveToken);
		Intent intent = getIntent();
		String titleString = intent.getStringExtra("title");
		String authorString = intent.getStringExtra("author");
		String expiresString = intent.getStringExtra("expires");
		returnURL = intent.getStringExtra("returnURL");
		readTemplate = intent.getStringExtra("readURL");
		coverURL = intent.getStringExtra("coverURL");
		
		title.setText(titleString);
		author.setText(authorString);
		expires.setText(expiresString);
		
		if(readTemplate==null){
			readButton.setVisibility(View.GONE);
		}else{
			readButton.setVisibility(View.VISIBLE);
		}
		
		getImage();
		
		returnButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				returnItem();
			}			
		});
		
		readButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				readBar.setVisibility(View.VISIBLE);
				getContentLink(readTemplate);
			}
			
		});
		
		
	}
	
	@Background
	public void getContentLink(String readURL){
        //ACPL: Removed Overdrive error URLs
		readURL = readURL.replace("{errorpageurl}", "");
		readURL = readURL.replace("{odreadauthurl}", "");
	
//		System.out.print(readURL);
//		OverdriveReadContentLink contentLink = client.getContentLink(readURL);
//		getContentLinkComplete(contentLink);
		DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
		HttpGet httpget = new HttpGet(readURL);
		// Depends on your web service
		SharedPreferences prefs = this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
		String overdriveToken = prefs.getString("overdriveToken", null);
		
		httpget.setHeader("Content-type", "application/json");
		httpget.setHeader("Authorization", "Bearer "+overdriveToken);
		InputStream inputStream = null;
		String result = null;
		try {
		    HttpResponse response = httpclient.execute(httpget);           
		    HttpEntity entity = response.getEntity();

		    inputStream = entity.getContent();
		    // json is UTF-8 by default
		    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
		    StringBuilder sb = new StringBuilder();

		    String line = null;
		    while ((line = reader.readLine()) != null)
		    {
		        sb.append(line + "\n");
		    }
		    result = sb.toString();
		} catch (Exception e) { 
		    // Oops
		}
		finally {
		    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
		}
		
		System.out.println(result);
		try {
			JSONObject jObject = new JSONObject(result);
			JSONObject linksObj = jObject.getJSONObject("links");
			JSONObject contentLinkObj = linksObj.getJSONObject("contentlink");
			
			String link = contentLinkObj.getString("href");
			System.out.println(link);
			getContentLinkComplete(link);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	@UiThread
	public void getContentLinkComplete(String link){
		readBar.setVisibility(View.INVISIBLE);
		if(link!=null){
			 Uri uri = Uri.parse(link);
			 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			 startActivity(intent);
		}
	}
	
	@Background
	public void returnItem(){
		client.returnBook(returnURL);
		returnItemComplete();
	}
	
	@UiThread
	public void returnItemComplete(){
		Toast toast = Toast.makeText(this, "Item returned.",
				Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
		
		finish();
	}
	
	@Background
	public void getImage(){
		URL urlObj;
		Bitmap img;
		try {
			urlObj = new URL(coverURL);
			System.out.print(coverURL);
			img = BitmapFactory.decodeStream(urlObj.openConnection().getInputStream());
			getImageComplete(img);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	@UiThread
	public void getImageComplete(Bitmap image){
		coverImage.setImageBitmap(image);
		coverImage.setVisibility(View.VISIBLE);
		coverBar.setVisibility(View.GONE);
	}

}
